class FetchersController < ApplicationController
  include ApplicationHelper
  
  before_filter :login_required, :administration_required
  
  def programs
    @replication_system = ReplicaSystem.find params[:repository_id]
    prepare_programs
    
    render :partial => 'programs_content'
  end
  
  def audio_assets
    @replication_system = ReplicaSystem.find params[:repository_id]
    prepare_audio_assets
    
    render :partial => 'audio_assets_content'
  end
  
  def remove_replicated_program
    @replication_system = ReplicaSystem.find params[:repository_id]
    program = Program.find(get_real_id(params[:id]))
    
    # Mark and save program in the replication system
    program.replica_systems.delete @replication_system
    prepare_programs
    
    render :partial => 'programs_content'
  end
  
  def add_replicated_program
    @replication_system = ReplicaSystem.find params[:repository_id]
    program = Program.find(get_real_id(params[:id]))
    
    # Mark and save program in the replication system
    program.replica_systems << @replication_system
    prepare_programs
    
    render :partial => 'programs_content'
  end
  
  ########################### audio_assets actions 
  
  def remove_replicated_asset
    @replication_system = ReplicaSystem.find params[:repository_id]
    audio_asset = AudioAsset.find(get_real_id(params[:id]))
    
    audio_asset.remove_replication(@replication_system)
    prepare_audio_assets
    
    render :partial => 'audio_assets_content'
  end
  
  def add_replicated_asset
    @replication_system = ReplicaSystem.find params[:repository_id]
    audio_asset = AudioAsset.find(get_real_id(params[:id]))

    # Create new replica
    audio_asset.replicate(@replication_system)
    prepare_audio_assets
    
    render :partial => 'audio_assets_content'
  end
  
  private
  def get_real_id(id)
    # Removes underscore(_) and the first element of passed id
    id.split("_")[1]
  end
  
  def prepare_programs
    all_programs = Program.find :all
    @replicated_programs = @replication_system.programs
    @non_replicated_programs = all_programs.reject{ |p| @replicated_programs.exists? p }
  end
  
  def prepare_audio_assets
    all_audio_assets = AudioAsset.find :all
    @replicated_assets = @replication_system.find_replicated_assets
    @non_replicated_assets = all_audio_assets.reject { |a| @replicated_assets.include? a }
  end
end
